#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/20 16:08
# @Author  : 李中华
# @Email   : 1260429766@qq.com
# @File    : readYAML.py
from ProgramPath import programPath
import os
import yaml
from common.logger import Log
logger = Log()


class ReadYAML:
    def __init__(self, yamlFile):
        '''
        yamlFile 为.yaml文件
        :param yamlFile:
        '''
        self.yamlFile = yamlFile
        if '.yaml' in self.yamlFile:
            pass
        else:
            self.yamlFile = yamlFile + '.yaml'
        yamlFilePath = os.path.join(programPath, 'page_element', self.yamlFile)

        try:
            with open(yamlFilePath, 'r', encoding='utf-8') as f:
                self.data = yaml.safe_load(f)
        except Exception as e:
            logger.info('异常：' + e)

    def __getitem__(self, item):
        data = self.data.get(item)
        if data:
            if '=' in str(data):
                name, data = tuple(str(data).split('=',1))
                return name, data
            else:
                return data
        raise Exception(f'{self.yamlFile}文件中没有 "{item}" 关键字')

    def getAllKeys(self):
        '''
        返回yaml文件中所有的关键字
        :return:
        '''
        return self.data.keys()

    @property
    def getAllData(self):
        return self.data

if __name__ == '__main__':
    # try:
    #     print(ReadYAML('admin.yaml')['a'])
    # except Exception as e:
    #     print(e)

    print(ReadYAML('admin.yaml')['children'])